﻿using Caliburn.Micro;
using SD.Infrastructure.DTOBase;
using SD.Infrastructure.WPF.Caliburn.Aspects;
using SD.Infrastructure.WPF.Caliburn.Base;
using SD.Infrastructure.WPF.Extensions;
using SD.Infrastructure.WPF.Models;
using SD.IOC.Core.Mediators;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel.Extensions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SlamDunk.MES.Client.ViewModels.Facility;
using SlamDunk.MES.IAppService.DTOs.Outputs.PlanContext;
using SlamDunk.MES.IAppService.DTOs.Outputs.ResourceContext;
using SlamDunk.MES.IAppService.Interfaces;
using SlamDunk.MES.Presentation.Models;
using SlamDunk.MES.Presentation.Models.NotifyModels;
using SlamDunk.MES.ReportView.Models;
using SlamDunk.ValueObjects.Enums;

namespace SlamDunk.MES.Client.ViewModels.Report
{
    /// <summary>
    /// 人员工时统计ViewModel
    /// </summary>
    public class WorkOrderActualPersonsReportViewModel : ScreenBase
    {
        #region # 字段及构造器
        /// <summary>
        /// 作业管理服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<IExecutionContract> _iExecutionContract;

        /// <summary>
        /// 资源定义服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<IResourceContract> _iResourceContract;

        /// <summary>
        /// 计划管理服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<IPlanContract> _planContract;

        /// <summary>
        /// 报表统计服务契约接口代理
        /// </summary>
        private readonly ServiceProxy<IReportContract> _iReportContract;

        /// <summary>
        /// 窗口管理器
        /// </summary>
        private readonly IWindowManager _windowManager;

        /// <summary>
        /// 依赖注入构造器
        /// </summary>
        public WorkOrderActualPersonsReportViewModel(ServiceProxy<IExecutionContract> iExecutionContract, ServiceProxy<IResourceContract> iResourceContract, ServiceProxy<IPlanContract> planContract, ServiceProxy<IReportContract> iReportContract, IWindowManager windowManager)
        {
            this._iExecutionContract = iExecutionContract;
            this._iResourceContract = iResourceContract;
            this._planContract = planContract;
            this._iReportContract = iReportContract;
            this._windowManager = windowManager;
        }
        #endregion

        #region 属性

        #region 开始时间 —— DateTime? StartTime
        /// <summary>
        /// 开始时间
        /// </summary>
        [DependencyProperty]
        public DateTime? StartTime { get; set; }
        #endregion

        #region 结束时间 —— DateTime? EndTime
        /// <summary>
        /// 结束时间
        /// </summary>
        [DependencyProperty]
        public DateTime? EndTime { get; set; }
        #endregion

        #region 人员列表
        /// <summary>
        /// 人员列表
        /// </summary>
        [DependencyProperty]
        public ObservableCollection<PersonInfo> Persons { get; set; }
        #endregion

        #region 已选人员
        /// <summary>
        /// 已选人员
        /// </summary>
        [DependencyProperty]
        public PersonInfo SelectedPerson { get; set; }
        #endregion

        #region 已选工厂模型 —— Node SelectedFacility
        /// <summary>
        /// 已选工厂模型
        /// </summary>
        [DependencyProperty]
        public Node SelectedFacility { get; set; }
        #endregion

        #region 人员统计列表
        /// <summary>
        /// 人员统计列表
        /// </summary>
        [DependencyProperty]
        public ObservableCollection<PersonSummaryNm> PersonSummaryReports { get; set; }
        #endregion
        #endregion

        #region # 方法

        //Initializations

        #region 初始化 —— override async Task OnInitializeAsync(CancellationToken cancellationToken)
        /// <summary>
        /// 初始化
        /// </summary>
        protected override async Task OnInitializeAsync(CancellationToken cancellationToken)
        {
            PageModel<PersonInfo> persons = await Task.Run(() => this._iResourceContract.Channel.GetPersonsByPage(
               null,//关键字
               null,//工厂模型Id
               null, //人员类Id
               1,
               int.MaxValue));
            this.Persons = new ObservableCollection<PersonInfo>(persons.Datas);
            StartTime = DateTime.Now.AddDays(-30);
            EndTime = DateTime.Now;
            await this.ReloadPersonSummaryReports();
        }
        #endregion

        //Actions
        #region 选择工厂模型 —— async void SelectFacility()
        /// <summary>
        /// 选择工厂模型
        /// </summary>
        public async void SelectFacility()
        {
            this.Busy();

            SelectFacilityViewModel viewModel = ResolveMediator.Resolve<SelectFacilityViewModel>();
            bool? result = await this._windowManager.ShowDialogAsync(viewModel);
            if (result == true)
            {
                this.SelectedFacility = viewModel.SelectedFacility;
            }

            this.Idle();
        }
        #endregion

        #region 清空工厂模型 —— async void ClearFacility()
        /// <summary>
        /// 清空工厂模型
        /// </summary>
        public async void ClearFacility()
        {
            this.SelectedFacility = null;
        }
        #endregion

        #region 查看人员工时统计 —— async void LoadPersonSummaryReports()
        /// <summary>
        /// 查看人员工时统计
        /// </summary>
        public async void LoadPersonSummaryReports()
        {
            await this.ReloadPersonSummaryReports();
        }
        #endregion

        #region 查看明细
        /// <summary>
        /// 查看明细
        /// </summary>
        public async void LookPersonSummaryReport(PersonSummaryNm personSummaryNm)
        {
            this.Busy();
            WorkOrderActualPersonsDetailtReportViewModel viewModel = ResolveMediator.Resolve<WorkOrderActualPersonsDetailtReportViewModel>();
            viewModel.Load(personSummaryNm);
            bool? result = await this._windowManager.ShowDialogAsync(viewModel);
            this.Idle();
        }
        #endregion 
        //Private

        #region 加载人员工时列表 —— async Task ReloadPersonSummaryReports()
        /// <summary>
        /// 加载人员工时列表
        /// </summary>
        private async Task ReloadPersonSummaryReports()
        {
            PersonSummaryReports = new ObservableCollection<PersonSummaryNm>();
            this.Busy();
            DateTime? startTime = this.StartTime;
            DateTime? endTime = this.EndTime;
            Guid? facilityId = this.SelectedFacility?.Id;
            //查询生成计划
            PageModel<ExecutionPlanInfo> pageModel = await Task.Run(() => this._planContract.Channel.GetExecutionPlansByPage(
                null,//关键字
                null, //产品Id
                null, //工艺Id
                null, //物料清单Id
                null,//生产计划Id
                null,//作业计划状态
                null, //审核状态
                true, //是否已生成工单
                null, //是否已质检
                startTime,//开始时间
                endTime, //结束时间
                facilityId,//工厂模型Id
                1, //页码
                int.MaxValue));
            //作业计划集合分组
            var executionPlanGroupList = pageModel.Datas.GroupBy(x => new { x.ProductId, x.ProductInfo, x.Status, x.FacilityId, x.FacilityInfo });
            foreach (var executionPlanInfo in pageModel.Datas)
            {
                //获取作业计划人员使用概要列表
                IEnumerable<PersonSummaryInfo> personSummaryList = this._iReportContract.Channel.GetExecutionPlanPersonUseSummaries(executionPlanInfo.Id);
                foreach (var personSummaryInfo in personSummaryList)
                {
                    //查询集合中是否存在重复员工
                    PersonSummaryNm personSummaryReport = PersonSummaryReports.SingleOrDefault(x => x.PersonId == personSummaryInfo.PersonId && x.PersonNo == personSummaryInfo.PersonNo && x.PersonName == personSummaryInfo.PersonName);
                    if (personSummaryReport == null)
                    {
                        PersonSummaryNm personSummaryNm = new PersonSummaryNm();
                        personSummaryNm.PersonId = personSummaryInfo.PersonId;
                        personSummaryNm.PersonNo = personSummaryInfo.PersonNo;
                        personSummaryNm.PersonName = personSummaryInfo.PersonName;
                        personSummaryNm.Manhour = personSummaryInfo.Manhour;
                        personSummaryNm.PlanStartTime = StartTime;
                        personSummaryNm.PlanEndTime = EndTime;
                        personSummaryNm.ExecutionPlanId = executionPlanInfo.Id;
                        ObservableCollection<PersonSummaryDetailNm> personSummaryDetailtReportInfos = new ObservableCollection<PersonSummaryDetailNm>();

                        PersonSummaryDetailNm personSummaryDetailNm = new PersonSummaryDetailNm();
                        personSummaryDetailNm.PersonNo = personSummaryInfo.PersonNo;
                        personSummaryDetailNm.PersonName = personSummaryInfo.PersonName;
                        personSummaryDetailNm.Manhour = personSummaryInfo.Manhour;
                        personSummaryDetailNm.ExecutionPlanNo = executionPlanInfo.Number;
                        personSummaryDetailNm.ExecutionPlanName = executionPlanInfo.Name;
                        personSummaryDetailNm.ProductionBatchNo = executionPlanInfo.ProductionBatchNo;
                        personSummaryDetailtReportInfos.Add(personSummaryDetailNm);
                        personSummaryNm.ExecutionPlanList = personSummaryDetailtReportInfos;
                        PersonSummaryReports.Add(personSummaryNm);
                    }
                    else
                    {
                        int index = PersonSummaryReports.IndexOf(personSummaryReport);
                        PersonSummaryReports.Remove(personSummaryReport);
                        personSummaryReport.Manhour += personSummaryInfo.Manhour;
                        PersonSummaryDetailNm personSummaryDetailNm = new PersonSummaryDetailNm();
                        personSummaryDetailNm.PersonNo = personSummaryInfo.PersonNo;
                        personSummaryDetailNm.PersonName = personSummaryInfo.PersonName;
                        personSummaryDetailNm.Manhour = personSummaryInfo.Manhour;
                        personSummaryDetailNm.ExecutionPlanNo = executionPlanInfo.Number;
                        personSummaryDetailNm.ExecutionPlanName = executionPlanInfo.Name;
                        personSummaryDetailNm.ProductionBatchNo = executionPlanInfo.ProductionBatchNo;
                        personSummaryReport.ExecutionPlanList.Add(personSummaryDetailNm);
                        this.PersonSummaryReports.Insert(index, personSummaryReport);
                    }
                }
            }
            if (SelectedPerson != null)
            {
                PersonSummaryReports = new ObservableCollection<PersonSummaryNm>(PersonSummaryReports.Where(x => x.PersonId == SelectedPerson.Id));
            }
            this.Idle();
        }
        #endregion
        #endregion

    }
}
